<script setup lang="ts">
import {ref, computed, defineProps} from 'vue'
import {orderCreate} from '../api/order.ts'
import {productInfo} from '../api/product.ts'

const price = ref()
const orderId = ref()
const deliverMethod = ref()
const quantity = ref(0)
const haveCreated = ref(true)
const priceSum = computed(() => price.value * quantity.value)
const createDisabled = computed(() => !deliverMethod.value || !quantity.value)
const emit = defineEmits(['open'])
const props = defineProps<{
  productId : number,
}>()


function openPay(){
  emit('open',orderId.value)
}
productInfo(props.productId).then(res =>{
  price.value = res.data.result.price
})
function createOrder() {
  orderCreate({
    commodityID: props.productId,
    deliveryMethod: deliverMethod.value,
    quantity: quantity.value
  }).then(res => {
    if (res.data.code === '000') {
      orderId.value = res.data.result.id
      ElMessage({
        message: "创建订单成功",
        type: 'success',
        center: true,
      })
      openPay()
    }
    else{
      ElMessage({
        message: res.data.msg,
        type: 'error',
        center: true,
      })
    }
  })
}



</script>

<template>
  <el-main>
    <el-form>
      <el-form-item label="购买数量">
        <el-input-number :disabled = !haveCreated v-model="quantity"></el-input-number>
      </el-form-item>

      <el-form-item  label = "提货方式">
        <el-select
            :disabled = !haveCreated
            v-model="deliverMethod"
            placeholder="请选择"
            style="width: 100%;"
        >
          <el-option value="0" label="快递送达"></el-option>
          <el-option value="1" label="到店自提"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="总价">
        {{priceSum}}元
      </el-form-item>

      <el-button  :disabled = createDisabled @click.prevent = "createOrder" class = "createbutton">创建订单</el-button>
    </el-form>
  </el-main>
</template>

<style scoped>

</style>